
using System;
using System.Collections.Generic;
using Habazie.kf2.Core;

namespace Habazie.kf2.Net
{
	/// <summary>
	///  	JabberClient with a few extras	
	/// </summary>
	public class ExtendedClient : jabber.client.JabberClient
	{
		private Dictionary<string, jabber.protocol.ProtocolHandler> m_handlers;
		
		public ExtendedClient() : base ()
		{
			m_handlers = new Dictionary<string, jabber.protocol.ProtocolHandler> ();
		}
		
		
		public XmppResponse BeginWrite (jabber.protocol.Element elem, jabber.protocol.ProtocolHandler handler)
		{
			string id = elem.GetAttribute ("id");
			XmppResponse res = new XmppResponse (id);
			m_handlers[id] = handler;
			Write (elem);
			return res;
		}
		
		public void CancelResponse (XmppResponse res)
		{
			m_handlers.Remove (res.ID);
		}
		
		protected override void OnElement (object o, System.Xml.XmlElement elem)
		{
//			Util.Debug ("net", "OnElement (<{0}>)", elem.LocalName);
			string id = elem.GetAttribute ("id");
			if (id == null) {
				base.OnElement (o, elem);
				return;
			}
				
//			Util.Debug ("net", "OnElement (id={1})(<{0}>)", elem.LocalName, id);
			jabber.protocol.ProtocolHandler handler = null;
			try {
				handler = m_handlers[id];
			} catch {
//				Util.Debug ("net", "No handler found...");
			}
			if (id != null && handler != null) {
//				Util.Debug ("net", "Calling handler");
				Gtk.Application.Invoke (delegate {
					handler (this, elem);
				});
			} else {
//				Util.Debug ("net", "Chaining to parent");
				base.OnElement (o, elem);
			}
		}
		
		void Connect ()
		{
			base.Connect ();
		}
	}
	
	public class XmppResponse {
		private string m_id;
		internal XmppResponse (string id)
		{
			m_id = id;
		}
		internal string ID {
			get { return m_id; }
		}
	}
}
